<template>
  <a-modal title="编辑用户" v-model:open="open" @ok="onSubmit" :confirmLoading="state.loading">
      <a-form :label-col="formCol.labelCol" :rules="rules" ref="formRef" :wrapper-col="formCol.wrapperCol"
          :model="form">
          <a-form-item label="用户名" name="username">
              <a-input show-count :maxlength="8" v-model:value="form.username" name="username" autocomplete="false"
                  placeholder="请输入用户名，少于8位字符" />
          </a-form-item>
          <a-form-item label="手机号码" name="mobile">
              <a-input name="mobile" v-model:value="form.mobile" autocomplete="false" placeholder="请输入11位数手机号码" />
          </a-form-item>
          <a-form-item label="密码" name="password">
              <a-input-password name="password" v-model:value="form.password" autocomplete="false"
                  placeholder="请输入密码，不少于6位字符" />
          </a-form-item>
          <a-form-item label="确认密码" name="confirmPassword">
              <a-input-password name="confirmPassword" v-model:value="form.confirmPassword" autocomplete="false"
                  placeholder="请再次输入密码" />
          </a-form-item>
          <a-form-item label="角色" name="role">
              <a-select :style="width.md" name="role" v-model:value="form.role" :options="roles"
                  placeholder="请选择角色" />
          </a-form-item>
          <a-form-item label="是否启用">
              <a-radio-group v-model:value="form.status">
                  <a-radio :value="1">是</a-radio>
                  <a-radio :value="0">否</a-radio>
              </a-radio-group>
          </a-form-item>
      </a-form>
  </a-modal>
</template>
<script setup lang="ts">
import { reactive, ref, watch } from 'vue';
import { formCol, width, roles } from '@/config';
import type { Rule } from 'ant-design-vue/es/form';
import { message, type FormInstance } from 'ant-design-vue';
import { hasPermission } from '@/hooks';
import { updateUser } from '@/server/modules/user';

const {userItem} = defineProps<{userItem?:UserInfo}>() 

const open = defineModel<boolean>('open')

const state = reactive({
    open: false,
    loading: false
})
const emits = defineEmits(['ok']);
// 定义表单实例
const formRef = ref<FormInstance>();
const form = reactive<UserInfoForm>({
    username: '',
    mobile: '',
    password: '',
    confirmPassword: '',
    role: undefined,
    status: 1
})
watch(() => userItem, (val) => {
    if (val) {
        Object.assign(form, val);
    }
},{immediate: true})
const validatePass = async (_rule: Rule, value: string) => {
    if (value === '') {
        return
    } else {
        if (form.confirmPassword !== '') {
            formRef.value?.validateFields('checkPass');
        }
        return Promise.resolve();
    }
};
const validatePass2 = async (_rule: Rule, value: string) => {
    if (value === '') {
        return
    } else if (value !== form.password) {
        return Promise.reject("两次输入密码不一致");
    } else {
        return Promise.resolve();
    }
};
// 定义表单验证规则
const rules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { max: 8, message: '用户名不能超过 8 个字符', trigger: 'blur' }
    ],
    mobile: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
    ],
    password: [
        { validator: validatePass, trigger: 'change' },
        { min: 6, message: '密码至少 6 个字符', trigger: 'blur' }
    ],
    confirmPassword: [
        { validator: validatePass2, trigger: 'change' }
    ],
    role: [
        { required: true, message: '请选择角色', trigger: 'change' }
    ]
};
const onSubmit = async () => {
    if (!hasPermission('update')) {
        return;
    }
    try {
        state.loading = true
        await formRef.value?.validate();
        const res = await updateUser(form);
        if(res.code === 200) {
            message.success('更新成功');
           open.value = false;
            emits('ok');
        }else{
            message.error(res.msg);
        }
    } catch (error) {
        return;
    } finally {
        setTimeout(() => {
            state.loading = false
        }, 3000)
    }
}
</script>
<style lang="css" scoped></style>